package model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


/**
 * 客户端请求响应体消息model
 */
public class ApiResultModel<T> {

    public final static int SUCCESS_CODE = 1;
    public final static int FAIL_CODE = 0;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getResult() {
        return result;
    }

    public void setResult(T result) {
        this.result = result;
    }

    private int code;
    private String message;
    private T result;

    public ApiResultModel() {}

    public ApiResultModel(int code, String messsage, T result) {
        this.code = code;
        this.message = messsage;
        this.result = result;
    }

    public String json() {
        return JSON.toJSONString(this);
    }

    /**
     * 解析特定类型result的json格式响应体
     */
    public static <T> ApiResultModel fromJson(String json, Class<T> resultClass) {
        JSONObject jsonObject = JSON.parseObject(json);
        ApiResultModel<T> apiResultModel = new ApiResultModel<>();
        apiResultModel.setCode(jsonObject.getInteger("code"));
        apiResultModel.setMessage(jsonObject.getString("message"));
        String resultStr = jsonObject.getString("result");
        apiResultModel.setResult(JSON.toJavaObject(JSON.parseObject(resultStr), resultClass));
        return apiResultModel;
    }

    /**
     * 解析json格式响应体，若带有result则转换为JsonObject或者JsonArray类型
     */
    public static ApiResultModel fromJson(String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        return JSON.toJavaObject(jsonObject, ApiResultModel.class);
    }

    public static <T> ApiResultModel parseListResult(String json, Class<T> listElementClass) {
        JSONObject jsonObject = JSON.parseObject(json);
        ApiResultModel apiResultModel = JSON.toJavaObject(jsonObject, ApiResultModel.class);
        apiResultModel.setResult(((JSONArray)apiResultModel.getResult()).toJavaList(listElementClass));
        return apiResultModel;
    }

    public static ApiResultModel successWithMessage(String message) {
        return new ApiResultModel<>(SUCCESS_CODE, message, null);
    }

    public static ApiResultModel failedWithMessage(String message) {
        return new ApiResultModel<>(FAIL_CODE, message, null);
    }

    public static ApiResultModel successWithObject(Object object) { return new ApiResultModel<>(SUCCESS_CODE, "success", object);}

}
